package org.dizena.gateway.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.dizena.common.base.bean.ApiResult;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@Component
public class LoginFilter implements GlobalFilter, Ordered {

    private List<String> guestPath;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getURI().getPath();
        // 检查uri是否需要鉴权认证
        for (String guest : guestPath) {
            if (uri.contains(guest)) {
                return chain.filter(exchange);
            }
        }

        HttpCookie cookie = request.getCookies().getFirst("s");
        String token;
        if (cookie != null) {
            token = cookie.getValue();
        } else {
            token = request.getHeaders().getFirst("s");
        }

        //验证token
        ServerHttpResponse response = exchange.getResponse();
        if (token == null) {
            ApiResult result = new ApiResult();
            result.setCode(HttpStatus.UNAUTHORIZED.value());
            result.setMsg("token is null");
            return getVoidMono(response, result);
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 2;
    }

    private Mono<Void> getVoidMono(ServerHttpResponse response, ApiResult result) {
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        DataBuffer dataBuffer = response.bufferFactory().wrap(toJsonStr(result).getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Flux.just(dataBuffer));
    }

    private String toJsonStr(Object obj) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            objectMapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON格式化对象错误");
        }
    }
}
